import 'package:cached_network_image/cached_network_image.dart';
import 'package:cher_flare/common/models/ly_user_works_model.dart';
import 'package:cher_flare/modules/login/models/ly_login_info_manager.dart';
import 'package:cher_flare/modules/login/models/ly_login_model.dart';
import 'package:cher_flare/personal_center/controllers/ly_personal_center_controller.dart';
import 'package:cher_flare/routes/app_pages.dart';
import 'package:cher_flare/utils/ly_data_manager.dart';
import 'package:cher_flare/utils/size_fit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../config/url_api.dart';
import '../../http/http_utils.dart';
import '../../modules/discovery/ly_discovery_card_item.dart';
import '../../utils/app_color.dart';

class LYPersonalCenterPage extends StatefulWidget {
  const LYPersonalCenterPage({super.key});

  @override
  State<LYPersonalCenterPage> createState() => _LYPersonalCenterPageState();
}

class _LYPersonalCenterPageState extends State<LYPersonalCenterPage> {
  final controller = Get.put(LYPersonalCenterController());

  void _avatarDidClick() {
    Get.toNamed(AppPages.personalInfoEditPage)?.then((value) {
      controller.userInfo = LYLoginInfoManager.getInstance.loginModel?.userInfo;
      controller.update(['userInfo']);
    });
  }

  void _copyButtonDidClick() {
    Clipboard.setData(ClipboardData(text: controller.userInfo?.userId));
    EasyLoading.showToast('Copied');
  }

  void _medalItemDidClick() {
    Get.toNamed(AppPages.medalPage)?.then((value) {
      controller.refreshUserInfo();
    });
  }

  void _blacklistItemDidClick() {
    Get.toNamed(AppPages.blockList);
  }

  void _followItemDidClick() {
    Get.toNamed(AppPages.followList);
  }

  void _aboutItemDidClick() {
    Get.toNamed(AppPages.aboutPage);
  }

  void _settingItemDidClick() {
    Get.toNamed(AppPages.settingPage);
  }

  void _coinItemDidClick() {
    Get.toNamed(AppPages.coinShopPage)?.then((value) {
      controller.refreshUserInfo();
    });
  }

  void _publishWorksDidClick() {
    Get.toNamed(AppPages.publishWorks)?.then((value) {
      _reloadWorks();
    });
  }

  void _worksDidClick(LYWorksModel model) {
    Get.toNamed(AppPages.worksDetailPage, arguments: {'works': model});
  }

  void _greatDidClick(LYWorksModel model) {
    model.isGreat = !(model.isGreat ?? false);
    LYDataManager.share.updateLocalWorksData();
    setState(() {});
  }

  void _deleteButtonDidClick(LYWorksModel model) {
    EasyLoading.show();
    LYDataManager.share.deleteWorks(model).then((value) {
      EasyLoading.dismiss();
      _reloadWorks();
    });
  }

  void _reloadWorks() {
    EasyLoading.show();
    LYDataManager.share.loadMyWorks().then((value) {
      controller.worksList = value;
      controller.update(['works']);
      EasyLoading.dismiss();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.colorD7FFDF,
        leadingWidth: 300,
        leading: InkWell(
          onTap: () => _coinItemDidClick(),
          child: Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.only(left: 18),
            child: Container(
              height: 36.px,
              width: 86.px,
              padding: const EdgeInsets.only(left: 10),
              alignment: Alignment.centerLeft,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/personal_cher_btn_bg.png'),
                  fit: BoxFit.fill,
                ),
                // borderRadius: BorderRadius.circular(18),
                // border: Border.all(color: AppColors.whiteColor, width: 1),
              ),
              child: GetBuilder(
                  init: controller,
                  id: 'userInfo',
                  builder: (_) {
                    return Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset(
                          'assets/images/personal_cher_flare_icon.png',
                          width: 27,
                          height: 22,
                        ),
                        const SizedBox(
                          width: 7,
                        ),
                        Text(
                          '${controller.userInfo?.availableCoins ?? 0}',
                          style: const TextStyle(
                              color: AppColors.color202020,
                              fontWeight: FontWeight.bold,
                              fontSize: 14),
                        ),
                      ],
                    );
                  }),
            ),
          ),
        ),
        elevation: 0,
        centerTitle: true,
      ),
      body: Stack(
        fit: StackFit.expand,
        children: [
          Positioned.fill(
              child: Image.asset(
            'assets/images/personal_center_ng.png',
            fit: BoxFit.cover,
          )),
          Column(
            children: [
              _makeUserWidget(),
              _makeFunctionWidget(),
              Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(top: 24.px, bottom: 24.px),
                child: Image.asset(
                  'assets/images/personal_my_atical_img.png',
                  width: 128,
                  height: 17,
                ),
              ),
              _makeArticalWidget(),
            ],
          ),
        ],
      ),
    );
  }

  Widget _makeArticalWidget() {
    return GetBuilder(
        init: controller,
        id: 'works',
        builder: (_) {
          if (controller.worksList != null &&
              controller.worksList!.isNotEmpty) {
            return Expanded(
              child: ListView.separated(
                padding: const EdgeInsets.all(16),
                itemBuilder: (ctx, index) {
                  final model = LYDataManager.share.allUserWorks[index];
                  return LYDiscoveryCardItem(
                    image: model.cover,
                    title: model.title,
                    content: model.description,
                    avatar: model.avatar,
                    nickName: model.nickname,
                    isGreat: model.isGreat ?? false,
                    isSave: model.isSave,
                    topIcon: 'works_delete_icon.png',
                    onTap: () {
                      _worksDidClick(model);
                    },
                    greatOnTap: () => _greatDidClick(model),
                    topIconOnTap: () => _deleteButtonDidClick(model),
                  );
                },
                separatorBuilder: (ctx, index) {
                  return const SizedBox(
                    height: 16,
                  );
                },
                itemCount: controller.worksList?.length ?? 0,
                cacheExtent: 320,
              ),
            );
          }
          return Expanded(
            child: InkWell(
              onTap: () => _publishWorksDidClick(),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Image.asset(
                    'assets/images/start_your_creation_img.png',
                    width: 189,
                    height: 143,
                  ),
                  SizedBox(
                    height: 20.px,
                  ),
                  Text(
                    'Start your creation.',
                    style: TextStyle(
                        color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.5),
                        fontSize: 16),
                  )
                ],
              ),
            ),
          );
        });
  }

  Widget _makeUserWidget() {
    return GetBuilder(
        init: controller,
        id: 'userInfo',
        builder: (_) {
          return InkWell(
            onTap: () => _avatarDidClick(),
            child: SizedBox(
              height: 122.px,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(
                    width: 38.px,
                  ),
                  SizedBox(
                    width: 88.px,
                    height: 88.px,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        Positioned(
                            child: ClipRRect(
                          borderRadius: BorderRadius.circular(44.px),
                          child: CachedNetworkImage(
                            imageUrl: controller.userInfo?.avatarUrl ?? '',
                            width: 88.px,
                            height: 88.px,
                            fit: BoxFit.cover,
                          ),
                        )),
                        Positioned(
                            left: 60.px,
                            top: 64.px,
                            child: Image.asset(
                              'assets/images/personal_camera_icon.png',
                              width: 26,
                              height: 26,
                            )),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: 20.px,
                  ),
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          controller.userInfo?.nickname ?? '',
                          style: const TextStyle(
                              color: AppColors.color202020,
                              fontWeight: FontWeight.bold,
                              fontSize: 18),
                        ),
                        SizedBox(
                          height: 18.px,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(
                              'ID：${controller.userInfo?.userId ?? ''}',
                              style: TextStyle(
                                  color:
                                      colorWithRGBA(r: 0, g: 0, b: 0, a: 0.5),
                                  fontSize: 14),
                            ),
                            SizedBox(
                              width: 4.px,
                            ),
                            InkWell(
                              onTap: () => _copyButtonDidClick(),
                              child: Container(
                                alignment: Alignment.center,
                                padding: EdgeInsets.symmetric(horizontal: 6.px),
                                height: 20.px,
                                decoration: BoxDecoration(
                                  boxShadow: [
                                    BoxShadow(
                                        color: colorWithRGBA(
                                            r: 0, g: 0, b: 0, a: 0.08),
                                        blurRadius: 20.0)
                                  ],
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular((10.px)),
                                ),
                                child: Text(
                                  'copy',
                                  style: TextStyle(
                                      color: AppColors.color44FC04,
                                      fontSize: 10.px),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        });
  }

  Widget _makeFunctionWidget() {
    return Container(
      height: 100.px,
      margin: EdgeInsets.only(left: 16.px, right: 16.px),
      decoration: BoxDecoration(
        color: AppColors.whiteColor,
        borderRadius: BorderRadius.circular(16.px),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: InkWell(
              onTap: () => _medalItemDidClick(),
              child: Container(
                alignment: Alignment.center,
                child: Image.asset(
                  'assets/images/personal_medal_icon.png',
                  width: 32.px,
                  height: 32.px,
                ),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () => _blacklistItemDidClick(),
              child: Container(
                alignment: Alignment.center,
                child: Image.asset(
                  'assets/images/personal_blacklist_icon.png',
                  width: 32.px,
                  height: 32.px,
                ),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () => _followItemDidClick(),
              child: Container(
                alignment: Alignment.center,
                color: AppColors.whiteColor,
                child: Image.asset(
                  'assets/images/personal_center_fllow.png',
                  width: 32.px,
                  height: 32.px,
                ),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () => _aboutItemDidClick(),
              child: Container(
                alignment: Alignment.center,
                color: AppColors.whiteColor,
                child: Image.asset(
                  'assets/images/personal_about_icon.png',
                  width: 32.px,
                  height: 32.px,
                ),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () => _settingItemDidClick(),
              child: Container(
                alignment: Alignment.center,
                child: Image.asset(
                  'assets/images/personal_setting_icon.png',
                  width: 32.px,
                  height: 32.px,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
